<template>
  <div style="padding:20px">
    <h1>{{id ? '编辑':'新建'}}英雄</h1>
    <el-alert v-if="id?true:false"
              title="如果要更改英雄职业，请删除该英雄后重新添加！"
              type="warning"
              center
              show-icon>
    </el-alert>
    <el-form :rules="rules"
             ref="ruleFormRef"
             :model="model">
      <div class="top">
        <div class="left">
          <el-form-item label="【英雄名称】"
                        prop="name">
            <el-input v-model="model.name"
                      placeholder="请输入英雄名称"
                      style="width:140px"></el-input>
          </el-form-item>
          <el-form-item label="【英雄称号】"
                        prop="title">
            <el-input v-model="model.title"
                      placeholder="请输入英雄称号"
                      style="width:140px"></el-input>
          </el-form-item>
          <el-form-item label="【英雄头像】"
                        prop="icon">
            <el-upload class="avatar-uploader"
                       :action="$upload"
                       accept="image/jpg,image/jpeg,image/png"
                       :before-upload="$handleBeforeUpload.handleBeforeUpload"
                       :show-file-list="false"
                       :on-success="afterUpload">
              <img v-if="model.icon"
                   :src="$upload+'/'+model.icon"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="【英雄职业】"
                        prop="f_id">
            <el-select v-model="model.f_id"
                       :disabled="id?true:false">
              <el-option v-for="(item,i) in $store.state.heros"
                         :label="item.name"
                         :value="item._id"
                         :key="i"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="【英雄评分】"
                        class="rate">
            <div class="rate-item">
              <span>【难度】</span>
              <el-rate :max="9"
                       show-score
                       v-model="model.scores.difficult" />
            </div>
            <div class="rate-item">
              <span>【技能】</span>
              <el-rate :max="9"
                       show-score
                       v-model="model.scores.skills" />
            </div>
            <div class="rate-item"><span>【攻击】</span>
              <el-rate :max="9"
                       show-score
                       v-model="model.scores.attack" />
            </div>
            <div class="rate-item">
              <span>【生存】</span>
              <el-rate :max="9"
                       show-score
                       v-model="model.scores.survive" />
            </div>
          </el-form-item>
          <el-form-item label="【出装推荐1】"
                        prop="items1">
            <el-cascader v-model="model.items1"
                         :options="ItemOptions"
                         expand-trigger='hover'
                         :props="cateProps">
            </el-cascader>
          </el-form-item>
          <el-form-item label="【出装推荐2】"
                        prop="items2">
            <el-cascader v-model="model.items2"
                         :options="ItemOptions"
                         expand-trigger='hover'
                         :props="cateProps">
            </el-cascader>
          </el-form-item>
          <el-form-item label="【召唤师技能】"
                        prop="Hero_Skill">
            <el-select v-model="model.Hero_Skill"
                       multiple
                       placeholder="请选择召唤师技能">
              <el-option v-for="item in $store.state.skills"
                         :key="item._id"
                         :label="item.name"
                         :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="【铭文推荐】"
                        prop="Insc">
            <el-cascader v-model="model.Insc"
                         :options="InscOptions"
                         expand-trigger='hover'
                         :props="cateProps">
            </el-cascader>
          </el-form-item>
        </div>
        <div class="right">
          <el-form-item>
            <el-carousel type="card"
                         :interval="4000"
                         height="200px"
                         v-show="model.skins.length === 0?false:true">
              <el-carousel-item v-for="(item,i) in this.model.skins"
                                :key="i">
                <div class="buttonDelete">
                  <img :src="$upload+'/'+item"
                       height="200px">
                  <img src="../../assets/delete.png"
                       class="delete"
                       @click="deleteSkin(item)">
                </div>
              </el-carousel-item>
            </el-carousel>
            【新增皮肤】
            <el-upload :action="$upload"
                       list-type="picture-card"
                       accept="image/jpg,image/jpeg,image/png"
                       :before-upload="$handleBeforeUpload.handleBeforeUpload"
                       :on-success="afterUpload1"
                       :on-remove="handleRemove"
                       multiple>
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button @click="addskills">添加技能</el-button>
          </el-form-item>
          <el-form-item class="skills">
            <div v-for="(item,i) in model.skills"
                 :key="i"
                 class="skill">
              <el-popover placement="bottom-start"
                          trigger="hover"
                          width="100">
                <el-button type="primary"
                           size="mini"
                           @click="editSkill(item)"><i class="el-icon-edit"></i></el-button>
                <el-button type="primary"
                           size="mini"
                           @click="deleteSkill(item)"><i class="el-icon-delete-solid"></i></el-button>
                <div style="font-size:10px">
                  {{item.descript}}
                </div>
                <img slot="reference"
                     :src="$upload+'/'+item.icon"
                     style="border-radius: 50%;width:100px;height:100px;">
              </el-popover>
              <div style="height:40px;font-size:25px">
                {{item.name}}
              </div>
            </div>
          </el-form-item>
        </div>
      </div>
      <div class="bottom">
        <el-form-item label="【铭文Tips】"
                      prop="usageTips">
          <el-input v-model="model.usageTips"
                    placeholder="请输入英雄使用技巧"></el-input>
        </el-form-item>
        <el-form-item label="【出装1Tips】"
                      prop="battleTips">
          <el-input v-model="model.battleTips"
                    placeholder="请输入英雄对抗技巧"></el-input>
        </el-form-item>
        <el-form-item label="【出装2Tips】"
                      prop="teamTips">
          <el-input v-model="model.teamTips"
                    placeholder="请输入英雄团战思路"></el-input>
        </el-form-item>
        <el-button type='primary'
                   @click="save"
                   style="float:right;margin-right:10px">保存</el-button>
      </div>
    </el-form>
    <el-dialog title="编辑技能"
               :visible.sync="dialogVisible"
               width="700px"
               center>
      <el-form :model="Skill"
               ref="FormRef"
               :rules="SkillFormRule">
        <el-container>
          <el-container>
            <el-aside width="210px">
              <el-form-item label="技能图片"
                            prop="icon">
                <el-upload class="avatar-uploader"
                           :action="$upload"
                           accept="image/jpg,image/jpeg,image/png"
                           :before-upload="$handleBeforeUpload.handleBeforeUpload"
                           :show-file-list="false"
                           :on-success="afterUpload2">
                  <img v-if="Skill.icon"
                       :src="$upload+'/'+Skill.icon"
                       class="avatar">
                  <i v-else
                     class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-aside>
            <el-main>
              <el-form-item label="技能名称"
                            prop="name">
                <el-input type="text"
                          v-model="Skill.name"></el-input>
              </el-form-item>
              <el-form-item label="技能描述"
                            prop="descript">
                <el-input type="textarea"
                          v-model="Skill.descript"></el-input>
              </el-form-item>
            </el-main>
          </el-container>
          <el-footer>
            <el-row>
              <el-col :span="8">
                <el-form-item label="技能消耗"
                              prop="consume">
                  <el-input v-model="Skill.consume"
                            style="width:100px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="技能cd"
                              prop="cd">
                  <el-input type="text"
                            v-model="Skill.cd"
                            style="width:200px"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-footer>
        </el-container>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="closeSkill">取 消</el-button>
        <el-button type="primary"
                   @click="saveSkill">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  props: ['id'],
  data () {
    return {
      model: {
        f_id: '',
        name: '',
        icon: '',
        title: '',
        scores: {
          difficult: 0,
          skills: 0,
          attack: 0,
          survive: 0
        },
        Hero_Skill: [],
        items1: [],
        items2: [],
        usageTips: '',
        battleTips: '',
        teamTips: '',
        skins: [],
        skills: [],
        Insc: []
      },
      ItemOptions: JSON.parse(sessionStorage.getItem('Item')),
      InscOptions: JSON.parse(sessionStorage.getItem('Insc')),
      dialogVisible: false,
      SkinTemp: [],
      Skill: {
        _id: 0,
        name: '',
        icon: '',
        descript: '',
        cd: '',
        consume: ''
      },
      cateProps: {
        value: '_id',
        label: 'name',
        children: 'children',
        multiple: true
      },
      SkillFormRule: {
        name: {
          required: true,
          message: '请填写技能名称',
          trigger: 'blur'
        },
        icon: {
          required: true,
          message: '请上传技能图标',
          trigger: 'blur'
        },
        descript: {
          required: true,
          message: '请填写技能描述',
          trigger: 'blur'
        },
        cd: {
          required: true,
          message: '请填写技能cd',
          trigger: 'blur'
        },
        consume: {
          required: true,
          message: '请填写技能消耗',
          trigger: 'blur'
        }
      },
      rules: {
        f_id: {
          required: true,
          message: '请选择英雄分类',
          trigger: 'blur'
        },
        name: {
          required: true,
          message: '请填写英雄名称',
          trigger: 'blur'
        },
        icon: {
          required: true,
          message: '请选择英雄头像',
          trigger: 'blur'
        },
        title: {
          required: true,
          message: '请填写英雄称号',
          trigger: 'blur'
        },
        usageTips: {
          required: true,
          message: '请输入英雄使用技巧',
          trigger: 'blur'
        },
        battleTips: {
          required: true,
          message: '请输入英雄对抗技巧',
          trigger: 'blur'
        },
        Hero_Skill: {
          required: true,
          message: '请选择召唤师技能',
          trigger: 'blur'
        },
        teamTips: {
          required: true,
          message: '请输入英雄团战思路',
          trigger: 'blur'
        },
        items1: {
          required: true,
          message: '请选择英雄顺风出装',
          trigger: 'blur'
        },
        Insc: {
          required: true,
          message: '请选择英雄推荐铭文',
          trigger: 'blur'
        },
        items2: {
          required: true,
          message: '请选择英雄逆风出装',
          trigger: 'blur'
        }
      }
    }
  },

  methods: {
    // 提交时只提交二级装备id
    Change (List) {
      List.forEach((item, index, arr) => {
        if (item instanceof Array) {
          arr[index] = item[1]
        }
      })
    },
    async save () {
      this.Change(this.model.items1)
      this.Change(this.model.items2)
      this.Change(this.model.Insc)
      this.SkinTemp.forEach(item => {
        this.model.skins.push(item)
      })
      this.model.skills.forEach(skill => {
        delete skill._id
      })
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.warning('请正确填写所有相关信息')
        }
        const res = this.id ? await this.$http.put('rest/Hero', { _id: this.model.f_id, index: this.id, children: this.model }) : await this.$http.post('rest/Hero/add', { _id: this.model.f_id, model: this.model })
        if (res.status !== 200) {
          return this.id ? this.$message.error('修改英雄失败！') : this.$message.error('添加英雄失败')
        }
        this.id ? this.$message.success('修改英雄成功！') : this.$message.success('添加英雄成功')
        this.$store.commit('UpdataHero', { _id: this.model.f_id, children: res.data.children })
        this.$router.push({ path: '/hero/list' })
        window.sessionStorage.setItem('ActivityName', this.model.f_id)
        window.sessionStorage.setItem('activePath', '/hero/list')
      })
    },
    afterUpload (res) {
      this.model.icon = res.url
    },
    afterUpload1 (res) {
      this.SkinTemp.push(res.url)
    },
    handleRemove (res) {
      this.SkinTemp.splice(res.url)
    },
    async fetch () {
      await this.$http.get(`/rest/Hero/${this.id}`).then(res => {
        if (res.status !== 200) {
          this.$router.push('/hero/list')
          window.sessionStorage.setItem('activePath', '/hero/list')
          return this.$message.error('获取英雄信息失败')
        }
        this.model = res.data
      })
    },
    deleteSkin (item) {
      this.$confirm('此操作将永久删除该皮肤, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.model.skins.splice(item, 1)
      })
    },
    addskills () {
      this.dialogVisible = true
      this.$data.Skill = { ...this.$options.data().Skill }
    },
    afterUpload2 (res) {
      this.Skill.icon = res.url
    },
    saveSkill () {
      this.$refs.FormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.warning('请正确填写所有相关信息')
        }
        if (this.Skill._id) {
          this.model.skills.forEach((skill, index, arr) => {
            if (skill._id === this.Skill._id) {
              arr[index] = this._.cloneDeep(this.Skill)
            }
          })
        } else {
          this.Skill._id = Math.random() * 9999999 + 1
          this.model.skills.push(this._.cloneDeep(this.Skill))
        }
        this.dialogVisible = false
      })
    },
    editSkill (item) {
      this.Skill = this._.cloneDeep(item)
      this.dialogVisible = true
    },
    deleteSkill (item) {
      this.$confirm('此操作将永久删除该技能, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.model.skills = this.model.skills.filter(items => items._id !== item._id)
      })
    },
    closeSkill () {
      this.dialogVisible = false
    }
  },
  created () {
    this.id && this.fetch()
  },
  watch: {
    '$route.path': function (newVal) {
      if (newVal === '/hero/create') {
        this.$data.model = { ...this.$options.data().model }
      }
    }
  }
}
</script>

<style scoped lang = "less">
.el-form {
  padding: 20px;
  display: flex;
  flex-direction: column;
  .top {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    .left {
      width: 50%;
      /deep/ .el-form-item__label {
        text-align: left;
      }
      .rate {
        display: flex;
        flex-direction: column;
        .rate-item {
          display: flex;
        }
      }
    }
    .right {
      width: 50%;
      .skills {
        /deep/ .el-form-item__content {
          width: 100%;
          display: flex;
          justify-content: space-around;
          .skill {
            display: flex;
            flex-direction: column;
            align-items: center;
          }
        }
      }
    }
  }
}
.el-cascader {
  .el-input {
    width: 300px;
  }
}
.buttonDelete {
  .delete {
    position: absolute;
    left: 39%;
    bottom: 20%;
    width: 40px;
    height: 40px;
  }
}
.el-dialog--center {
  .el-dialog__body {
    padding-bottom: 0px;
  }
}
.el-alert {
  margin-bottom: 10px;
}
.el-input--suffix {
  .el-input__inner {
    width: 300px;
  }
}
</style>
